package net.feling.mcloud.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.*;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import net.feling.mcloud.R;
import net.feling.mcloud.connection.ConnectService;

import java.net.InetSocketAddress;

public class LoginActivity extends Activity implements View.OnClickListener, ServiceConnection {
    private EditText etAddress, etPort, etDeviceId;
    private Button btnConnect, btnSync;
    private ConnectService.MyBinder binder = null;
    private InetSocketAddress address;
    private Intent intent;
    private boolean isSync = false;
    private boolean timeout = false;
    private ProgressDialog dialog;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);
        etAddress = (EditText) findViewById(R.id.address);
        etPort = (EditText) findViewById(R.id.port);
        etDeviceId = (EditText) findViewById(R.id.device_id);

        btnConnect = (Button) findViewById(R.id.btn_login);
        btnSync = (Button) findViewById(R.id.btn_register);
        btnConnect.setOnClickListener(this);
        btnSync.setOnClickListener(this);
        intent = new Intent(this, ConnectService.class);
        dialog = new ProgressDialog(LoginActivity.this);
        dialog.setTitle("正在连接服务器");
        dialog.setMessage("connecting...");
        dialog.setCancelable(false);

        // get IMIE id
        TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
        String deviceId = tm.getDeviceId();
        etDeviceId.setText(deviceId);

    }

    @Override
    protected void onStart() {
        super.onStart();
        bindService(intent, this, Context.BIND_AUTO_CREATE);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_register:
                //将输入的连接参数传入Service
                String mAddress = etAddress.getText().toString();
                int mPort = Integer.parseInt(etPort.getText().toString());
                address = new InetSocketAddress(mAddress, mPort);
                binder.setSocketAddress(address);
                isSync = true;
                timeout = false;
                if (binder != null) {
                    binder.getService().setConnector();
                }
                Toast.makeText(this, "提交成功", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_login:
                if (!isSync) {
                    Toast.makeText(this, "请先提交数据", Toast.LENGTH_SHORT).show();
                    break;
                }
                if (binder == null) {
                    Toast.makeText(this, "binder is null", Toast.LENGTH_SHORT).show();
                    break;
                }

                //每次按连接按钮都会启动一次服务
                startService(intent);
                dialog.show();
                controlDialog();
                break;
            default:
                break;
        }
    }

    public void startMain() {
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(this);
        Log.d("登陆Activity", "--->onDestroy");
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        binder = (ConnectService.MyBinder) service;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                dialog.dismiss();
                if (timeout) {
                    AlertDialog.Builder aDialog = new AlertDialog.Builder(LoginActivity.this);
                    aDialog.setTitle("网络故障");
                    aDialog.setMessage("无法连接服务器，请检查网络或IP后重试");
                    aDialog.setCancelable(false);
                    aDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface adialog, int which) {
                            timeout = false;
                            adialog.dismiss();
                        }
                    });
                    aDialog.show();
                } else {
                    startMain();
                }
            }
        }
    };


    /**
     * 用于管理Dialog对话框的方法，用Handler异步处理Service中子线程的返回结果
     */
    public void controlDialog() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = Message.obtain();
                while (!binder.getService().isConnected()) {
                    message.what = 0;
                    if (binder.getService().isTimeout()) {
                        timeout = true;
                        break;
                    }
                }
                message.what = 1;
                handler.sendMessage(message);
            }
        });
        thread.start();
    }
}